import * as fs from 'fs';
import * as path from 'path';
import * as yaml from 'js-yaml';

type Config = { app?: { name: string; host: string; port: number; }; assets?: string; public?: string; log4js?: { level: string; }; database?: { client: string; driver: string; host: string; port: number; user: string; password: string; database: string; init: { mode: string; schema: string; data: string; }; }; redis?: { host: string; port: string; password: string; }; rabbitmq?: { host: string; port: number; user: string; password: string; }; nacos?: { server: { host: string; port: number; }; namespace: string; }; satoken?: {"token-name": string;"jwt-secret-key": string;} };

export function init() {
  const config:Config = yaml.load(
    fs.readFileSync(
      path.join(__dirname, 'assets/config.yaml')
  ).toString());
  config.assets = path.join(__dirname, 'assets');
  config.public = path.join(process.cwd(), 'public');
  if (config.database) {
    let {client, database:db} = config.database;
    if (client == 'sqlite') {
      if (!path.isAbsolute(db)) {
        if (db.includes("${public}")) {
          db = db.replace('${public}','');
        }
        config.database.database = path.join(config.public, db);
      }
    }
    let schema = config.database.init.schema;
    if (!path.isAbsolute(schema)) {
      if (schema.includes("${assets}")) {
        schema = schema.replace('${assets}','');
      }
      config.database.init.schema = path.join(config.assets, schema);
    }
    let data = config.database.init.data;
    if (!path.isAbsolute(data)) {
      if (data.includes("${assets}")) {
        data = data.replace('${assets}','');
      }
      config.database.init.data = path.join(config.assets, data);
    }
  }
  global.__config = config;
}

export function get() {
  if(!global.config) {
    init();
  }
  const config: Config = global.__config;
  return config;
}

export const config = get();

export default {
  init,
  get,
  config: get()
}
